
use actix_web::{get, HttpRequest, Responder,Error};
use walkdir::WalkDir;

#[get("/ping")]
async fn ping(req:HttpRequest) -> impl Responder{
    format!("hello! {}",req.connection_info().remote_addr().unwrap_or("I dont know you"))
}

#[get("/file/ls")]
async fn ls() -> Result<String,Error>{
    let files:String = WalkDir::new("file").into_iter()
    .filter_map(Result::ok)
    .filter(|e| !e.file_type().is_dir())
    .map(|e|String::from(e.path().as_os_str().to_string_lossy())+"\n")
    .collect();
    return Ok(files);
}
#[get("/file/{filename:.*}")]
async fn index(req: HttpRequest) -> Result<actix_files::NamedFile, Error> {
    let path = format!("file/{}",req.match_info().query("filename"));
    let file = actix_files::NamedFile::open(path)?;
    Ok(file)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};
    HttpServer::new(|| {
        App::new()
        .service(ls)
        .service(ping)
        .service(index)
    })
    .bind("0.0.0.0:80")?
    .run()
    .await
}
